package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.SmsAnswerPojo;
import com.xbongbong.paas.redis.RedisConstant;
import com.xbongbong.paas.service.SMSSpaceService;
import com.xbongbong.paas.service.SmsReplyService;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.dynamic.crm.strategy.SmsDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicSmsDTO;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.ContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ClueErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.sms.model.SmsConfigModel;
import com.xbongbong.pro.sms.model.SmsReplyModel;
import com.xbongbong.pro.sms.model.SmsStatusModel;
import com.xbongbong.pro.sms.pojo.SmsExplainPojo;
import com.xbongbong.pro.sms.pojo.SmsReplyLogPojo;
import com.xbongbong.pro.sms.pojo.SmsReplyPojo;
import com.xbongbong.pro.sms.pojo.SmsSendPojo;
import com.xbongbong.pro.sms.pojo.dto.SmsBalanceDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsDealingDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsMobileListDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsPullReplyDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsReplyLogListDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsSearchListDTO;
import com.xbongbong.pro.sms.pojo.dto.SmsSignDTO;
import com.xbongbong.pro.sms.pojo.vo.SmsBalanceVO;
import com.xbongbong.pro.sms.pojo.vo.SmsDealingVO;
import com.xbongbong.pro.sms.pojo.vo.SmsMobileListVO;
import com.xbongbong.pro.sms.pojo.vo.SmsPullReplyVO;
import com.xbongbong.pro.sms.pojo.vo.SmsReplyLogListVO;
import com.xbongbong.pro.sms.pojo.vo.SmsReplyVO;
import com.xbongbong.pro.sms.pojo.vo.SmsSearchListVO;
import com.xbongbong.pro.sms.pojo.vo.SmsSearchVO;
import com.xbongbong.pro.sms.pojo.vo.SmsSendVO;
import com.xbongbong.pro.sms.pojo.vo.SmsSignVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.constant.UserConstant;
import com.xbongbong.saas.domain.entity.SmsConfigEntity;
import com.xbongbong.saas.domain.entity.SmsReplyEntity;
import com.xbongbong.saas.domain.entity.SmsStatusEntity;
import com.xbongbong.saas.enums.SmsModuleTypeEnum;
import com.xbongbong.saas.enums.SmsTemplateSendApiEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.paas.toolbox.util.DateUtil.SDFYMDHM;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @version v1.0
 * @auther: youli.chen
 * @description: 回复短信方法实现类
 * @date: 2019-11-28 17:42
 * @since v1.0
 */
@Service("smsReplyService")
public class SmsReplyServiceImpl implements SmsReplyService {

    private static final Logger LOG = LoggerFactory.getLogger(SmsReplyServiceImpl.class);

    @Resource
    private SmsReplyModel smsReplyModel;
    @Resource
    private SmsStatusModel smsStatusModel;
    @Resource
    private UserModel userModel;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private SmsConfigModel smsConfigModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;

    /**
     * 通过crontab定时任务不停的拉取回复短信
     *
     * @param smsPullReplyDTO 入参
     * @return
     * @author youli.chen
     * @version
     * @since
     */
    @Override
    public SmsPullReplyVO cronTabPullSmsReply(SmsPullReplyDTO smsPullReplyDTO) throws XbbException {
        SmsPullReplyVO smsPullReplyVO = new SmsPullReplyVO();
        String key = smsPullReplyDTO.getKey();
        if (!Objects.equals(key, BasicConstant.TASK_SECRET_KEY)) {
            LOG.error("回复短信定时拉取任务脚本校验 密码错误，停止定时任务！stop-task");
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100066);
        }
        LOG.info("cronTabPullSmsReply.param:" + smsPullReplyDTO);
        pullSmsReply(smsPullReplyDTO.getSendApi());
        return smsPullReplyVO;
    }

    /**
     * 拉取回复短信
     * @throws XbbException
     */
    private void pullSmsReply(Integer sendApi) throws XbbException {
        List<SmsAnswerPojo> retList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.equals(sendApi, SmsTemplateSendApiEnum.SPACE_IMAGINATION_MARKET_AMOUNT.getCode())) {
            // 4：空间畅想营销账号
            retList = SMSSpaceService.getMarketAnswerMsg();
        } else if (Objects.equals(sendApi, SmsTemplateSendApiEnum.SPACE_IMAGINATION_NOTICE_AMOUNT.getCode())) {
            // 3：空间畅想通知账号
            retList = SMSSpaceService.getNoticeAnswerMsg();
        }
        LOG.info("pullSmsReply -> retList:" + retList);
        Integer count = retList.size();
        if(Objects.equals(0, count)) {
            return;
        }

        List<SmsReplyEntity> smsReplyEntityList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for(SmsAnswerPojo smsAnswerPojo : retList){
            // 回复短信入库
            saveReplySms(smsAnswerPojo, smsReplyEntityList);
        }
        LOG.info("pullSmsReply -> insertBatch:" + smsReplyEntityList);
        smsReplyModel.insertBatch(smsReplyEntityList);

        // 动态
        try{
            SmsDynamicStrategy smsDynamicStrategy = dynamicStrategyFactory.getSmsDynamicStrategyByBusinessType(XbbRefTypeEnum.UNKNOWN.getCode());
            smsDynamicStrategy.reply(new DynamicSmsDTO().setSmsReplyEntities(smsReplyEntityList));
        }catch (Exception e){
            LOG.error("短信回复动态失败", e);
        }

        // 超过1000条，再次查询
        if(count > SMSSpaceService.MAX_PULL_NUM) {
            pullSmsReply(sendApi);
        }
    }

    /**
     * 回复短信入库
     *
     * @param smsAnswerPojo      短信回复实体
     * @param smsReplyEntityList 回复短信集合
     * @throws XbbException
     */
    private void saveReplySms(SmsAnswerPojo smsAnswerPojo, List<SmsReplyEntity> smsReplyEntityList) throws XbbException {
        String sourcePhone = smsAnswerPojo.getSourcePhone();
        String answerSmsContent = smsAnswerPojo.getAnswerSmsContent();
        Long replyTime = smsAnswerPojo.getReplyTime();
        String reference = smsAnswerPojo.getReference();

        SmsReplyEntity replyEntity = new SmsReplyEntity();

        // 根据号码查询最后一条发送短信的数据(范围：客户，联系人, 工单),entity,sendId
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", reference);
        param.put("mobile", sourcePhone);
        param.put("start", 0);
        param.put("pageNum", 1);
        param.put("orderByStr", "id desc");
        List<SmsStatusEntity> smsStatusEntityList = smsStatusModel.findEntitys(param);
        if(smsStatusEntityList.size() > 0){
            SmsStatusEntity smsStatusEntity = smsStatusEntityList.get(0);
            replyEntity.setAppId(smsStatusEntity.getAppId());
            replyEntity.setMenuId(smsStatusEntity.getMenuId());
            replyEntity.setFormId(smsStatusEntity.getFormId());
            replyEntity.setAttr(smsStatusEntity.getAttr());
            replyEntity.setSaasMark(smsStatusEntity.getSaasMark());
            replyEntity.setSenderId(smsStatusEntity.getUserId());
            replyEntity.setRefId(smsStatusEntity.getRefId());
            replyEntity.setRefType(smsStatusEntity.getRefType());
            replyEntity.setReplyName(smsStatusEntity.getReceiver());
        } else {
            // 对于初始公司没有一条短信
            replyEntity.setSenderId("");
        }
        // 拓展标识字段(暂定为corpid)
        replyEntity.setCorpid(reference);
        replyEntity.setReplyTime(replyTime);
        replyEntity.setMobile(sourcePhone);
        replyEntity.setContent(answerSmsContent);
        smsReplyEntityList.add(replyEntity);
    }

    /**
     * 表单列表
     *
     * @param smsSearchListDTO 关联业务DTO
     * @return 表单VO
     * @throws XbbException 业务异常
     */
    @Override
    public SmsSearchListVO getSmsSearchList(SmsSearchListDTO smsSearchListDTO) throws XbbException {
        SmsSearchListVO smsSearchListVO = new SmsSearchListVO();
        List<SmsSearchVO> list = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<SmsModuleTypeEnum> smsModuleTypeEnumList = SmsModuleTypeEnum.getAllEnum();
        smsModuleTypeEnumList.forEach(smsModuleTypeEnum -> {
            SmsSearchVO smsSearchVO = new SmsSearchVO();
            smsSearchVO.setRefType(smsModuleTypeEnum.getCode());
            smsSearchVO.setName(smsModuleTypeEnum.getName());
            list.add(smsSearchVO);
        });
        smsSearchListVO.setList(list);
        return smsSearchListVO;
    }

    /**
     * 查询当前公司是不是短信初始用户(有没有申请过签名)
     *
     * @param smsSignDTO 查询当前公司是不是短信初始用户DTO
     * @return 签名
     * @throws XbbException 业务异常
     */
    @Override
    public SmsSignVO smsSign(SmsSignDTO smsSignDTO) throws XbbException {
        SmsSignVO smsSignVO = new SmsSignVO();
        String corpid = smsSignDTO.getCorpid();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        List<SmsConfigEntity> smsConfigList = smsConfigModel.findEntitys(param);
        if(Objects.equals(smsConfigList.size(), 0)){
            smsSignVO.setApplySign(false);
        } else {
            SmsConfigEntity smsConfigEntity = smsConfigList.get(0);
            String sign = smsConfigEntity.getSign();
            if(StringUtil.isNotEmpty(sign)){
                smsSignVO.setApplySign(true);
                smsSignVO.setSmsSign(sign);
            } else {
                smsSignVO.setApplySign(false);
                smsSignVO.setSmsSign(sign);
            }
        }
        return smsSignVO;
    }

    /**
     * 查询当前公司短信账户余额
     *
     * @param smsBalanceDTO 查询当前公司短信账户余额DTO
     * @return 账户余额
     * @throws XbbException 业务异常
     */
    @Override
    public SmsBalanceVO getSmsBalance(SmsBalanceDTO smsBalanceDTO) throws XbbException {
        SmsBalanceVO smsBalanceVO = new SmsBalanceVO();
        String corpid = smsBalanceDTO.getCorpid();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        List<SmsConfigEntity> smsConfigList = smsConfigModel.findEntitys(param);
        if(Objects.equals(smsConfigList.size(), 0)){
            smsBalanceVO.setSmsBalance(0.00D);
        } else {
            SmsConfigEntity smsConfigEntity = smsConfigList.get(0);
            Double smsBalance = smsConfigEntity.getSmsBalance() == null ? Double.valueOf(0.00D) : smsConfigEntity.getSmsBalance();
            smsBalanceVO.setSmsBalance(smsBalance);
        }
        return smsBalanceVO;
    }

    /**
     * 对象对应的号码(短信号码)
     *
     * @param smsMobileListDTO 对象对应的号码(短信号码)DTO
     * @return 对象对应的号码(短信号码)VO
     * @throws XbbException 业务异常
     */
    @Override
    public SmsMobileListVO smsMobileList(SmsMobileListDTO smsMobileListDTO) throws XbbException {
        SmsMobileListVO smsMobileListVO = new SmsMobileListVO();

        String corpid = smsMobileListDTO.getCorpid();
        List<Long> dataIdIn = smsMobileListDTO.getDataIdIn();
        Integer numberType = smsMobileListDTO.getNumberType();
        Integer businessType = smsMobileListDTO.getBusinessType();

        // 返回的数据全部进行过滤，只保留返回有效的手机号码
        List<String> mobileList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(numberType == null){
            Long dataId = dataIdIn.get(0);
            PaasFormDataEntityExt paasFormDataEntityExt = saasGetHelp.getFormData(dataId, corpid, businessType);
            if (paasFormDataEntityExt == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            JSONObject data = paasFormDataEntityExt.getData();
            // 客户详情中查询
            if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                // 客户电话
                JSONArray customerPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(customerPhoneArray)) {
                    for (Object object : customerPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
                // 客户主联系人电话没有在客户解释中，直接查询出所有联系人中所有关联此客户号码(联系人包括主联系人)
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME), dataId));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(FieldTypeEnum.DATAID.getAlias());
                fieldList.add(StringConstant.JSON_DATA);
                List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT,boolQueryBuilder,PaasFormDataEntityExt.class, fieldList);
                if (CollectionsUtil.isNotEmpty(paasFormDataEntityList)) {
                    for(PaasFormDataEntityExt entityExt : paasFormDataEntityList){
                        JSONObject contactData = entityExt.getData();
                        // 客户联系人电话
                        JSONArray customerContactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactData, ContactEnum.PHONE.getAttr(), new JSONArray());
                        if(CollectionsUtil.isNotEmpty(customerContactPhoneArray)){
                            for (Object object : customerContactPhoneArray) {
                                JSONObject phoneJsonObject = (JSONObject) object;
                                String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                                Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                                if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                                    mobileList.add(tel);
                                }
                            }
                        }
                    }
                }
            } else if(Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())){
                // 联系人详情中查询
                // 联系人电话
                JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ContactEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(contactPhoneArray)) {
                    for (Object object : contactPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
            } else if(Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())){
                // 工单详情中查询
                // 工单联系人电话以及“关联联系人”的联系方式
                JSONArray workOrderInfoArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, WorkOrderEnum.CONTACT_INFORMATION.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(workOrderInfoArray)) {
                    for (Object object : workOrderInfoArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
                // 工单“关联联系人”的联系方式
                Long workOrderContactId = FastJsonHelper.getLongOrDefaultFromFormData(data, WorkOrderEnum.LINK_CONTACT.getAttr(), null);
                if (Objects.nonNull(workOrderContactId)){
                    // 联系人
                    PaasFormDataEntityExt contactEntityExt = saasGetHelp.getFormData(workOrderContactId, corpid, XbbRefTypeEnum.CONTACT.getCode());
                    if (contactEntityExt != null) {
                        JSONObject contactData = contactEntityExt.getData();
                        JSONArray workOrderContactInfoArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactData, ContactEnum.PHONE.getAttr(), new JSONArray());
                        if (CollectionsUtil.isNotEmpty(workOrderContactInfoArray)) {
                            for (Object object : workOrderContactInfoArray) {
                                JSONObject phoneJsonObject = (JSONObject) object;
                                String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                                Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                                if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                                    mobileList.add(tel);
                                }
                            }
                        }
                    }
                }
            }
        }
        // 查询批量发送需要的号码
        if(Objects.equals(numberType, 1)){
            // 客户主联系人电话
            BoolQueryBuilder customerBuilder = boolQuery();
            customerBuilder.filter(termQuery("corpid.keyword", corpid));
            customerBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            customerBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);
            IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
            List<PaasFormDataEntityExt> customerList = esHelper.findByScroll(indexTypeEnum, customerBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(customerList)) {
                throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
            }
            List<Long> customerIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            customerList.forEach(customer -> customerIdIn.add(customer.getDataId()));
            // 查询客户的主联系人
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termQuery("data." + ContactEnum.IS_MAIN.getAttr(), 1));
            boolQueryBuilder.filter(termsQuery(ContactEnum.getEsAttr4Keyword(ContactEnum.CUSTOMER_NAME),customerIdIn));
            List<String> contactFieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);
            List<PaasFormDataEntityExt> paasFormDataEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT,boolQueryBuilder,PaasFormDataEntityExt.class, contactFieldList);
            if (CollectionsUtil.isNotEmpty(paasFormDataEntityList)) {
                for(PaasFormDataEntityExt contact : paasFormDataEntityList){
                    JSONObject contactData = contact.getData();
                    JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactData, ContactEnum.PHONE.getAttr(), new JSONArray());
                    if (CollectionsUtil.isNotEmpty(contactPhoneArray)) {
                        for (Object object : contactPhoneArray) {
                            JSONObject phoneJsonObject = (JSONObject) object;
                            String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                            Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                            if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                                mobileList.add(tel);
                            }
                        }
                    }
                }
            }
        }
        if(Objects.equals(numberType, 2)){
            // 任一客户电话
            BoolQueryBuilder customerBuilder = boolQuery();
            customerBuilder.filter(termQuery("corpid.keyword", corpid));
            customerBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            customerBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);

            IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
            List<PaasFormDataEntityExt> customerList = esHelper.findByScroll(indexTypeEnum, customerBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(customerList)) {
                throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
            }
            for(PaasFormDataEntityExt customer : customerList){
                JSONObject customerData = customer.getData();
                JSONArray customerPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(customerData, CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(customerPhoneArray)) {
                    for (Object object : customerPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                            break;
                        }
                    }
                }
            }
        }
        if(Objects.equals(numberType, 3)){
            // 全部客户电话
            BoolQueryBuilder customerBuilder = boolQuery();
            customerBuilder.filter(termQuery("corpid.keyword", corpid));
            customerBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            customerBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);

            IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());
            List<PaasFormDataEntityExt> customerList = esHelper.findByScroll(indexTypeEnum, customerBuilder, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(customerList)) {
                throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001);
            }
            for(PaasFormDataEntityExt customer : customerList){
                JSONObject customerData = customer.getData();
                JSONArray customerPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(customerData, CustomerManagementEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(customerPhoneArray)) {
                    for (Object object : customerPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
            }
        }
        if(Objects.equals(numberType, 4)){
            // 任一联系人电话
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> contactFieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);
            List<PaasFormDataEntityExt> contactEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT,boolQueryBuilder,PaasFormDataEntityExt.class, contactFieldList);
            if (Objects.isNull(contactEntityList)) {
                throw new XbbException(ContactErrorCodeEnum.API_ERROR_204006);
            }
            for(PaasFormDataEntityExt contact : contactEntityList){
                JSONObject contactData = contact.getData();
                JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactData, ContactEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(contactPhoneArray)) {
                    for (Object object : contactPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                            break;
                        }
                    }
                }
            }
        }
        if(Objects.equals(numberType, 5)){
            // 全部联系人电话
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
            List<String> contactFieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);
            List<PaasFormDataEntityExt> contactEntityList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTACT,boolQueryBuilder,PaasFormDataEntityExt.class, contactFieldList);
            if (Objects.isNull(contactEntityList)) {
                throw new XbbException(ContactErrorCodeEnum.API_ERROR_204006);
            }
            for(PaasFormDataEntityExt contact : contactEntityList){
                JSONObject contactData = contact.getData();
                JSONArray contactPhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(contactData, ContactEnum.PHONE.getAttr(), new JSONArray());
                if (CollectionsUtil.isNotEmpty(contactPhoneArray)) {
                    for (Object object : contactPhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
            }
        }

        if(Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())){
            smsMobileList4Clue(numberType,corpid,dataIdIn,mobileList);
        }
        smsMobileListVO.setMobileList(mobileList);
        Integer mobileCount = mobileList.isEmpty() ? Integer.valueOf(0) : mobileList.size();
        smsMobileListVO.setMobileCount(mobileCount);
        return smsMobileListVO;
    }


    private void smsMobileList4Clue(Integer numberType,String corpid, List<Long> dataIdIn,List<String> mobileList) throws XbbException{
        //线索支持发短信
        BoolQueryBuilder clueQuery = boolQuery();
        clueQuery.filter(termQuery("corpid.keyword", corpid));
        clueQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        clueQuery.filter(termsQuery(StringConstant.DATA_ID, dataIdIn));
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), StringConstant.JSON_DATA);
        List<PaasFormDataEntityExt> clueList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CLUE, clueQuery, PaasFormDataEntityExt.class, fieldList);
        if (Objects.isNull(clueList)) {
            throw new XbbException(ClueErrorCodeEnum.API_ERROR_1110023);
        }
        for(PaasFormDataEntityExt clue : clueList){
            JSONObject clueData = clue.getData();
            JSONArray cluePhoneArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(clueData, ClueEnum.PHONE.getAttr(), new JSONArray());
            if (CollectionsUtil.isNotEmpty(cluePhoneArray)) {
                if(Objects.equals(numberType,BasicConstant.SEVEN)){
                    for (Object object : cluePhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                            break;
                        }
                    }
                }else {
                    for (Object object : cluePhoneArray) {
                        JSONObject phoneJsonObject = (JSONObject) object;
                        String tel = phoneJsonObject.getString(StringConstant.PHONE_TEL_ATTR);
                        Integer telLength = tel == null ? Integer.valueOf(0) : tel.length();
                        if(telLength >= UserConstant.MOBILE_PHONE_NUM_COMMON_LENGTH){
                            mobileList.add(tel);
                        }
                    }
                }
            }
        }
    }



    /**
     * 根据号码查询发送短信以及回复短信(短信往来)
     *
     * @param smsDealingDTO 短信往来DTO
     * @return 短信往来记录
     * @throws XbbException 业务异常
     */
    @Override
    public SmsDealingVO smsDealingList(SmsDealingDTO smsDealingDTO) throws XbbException {
        SmsDealingVO smsDealingVO = new SmsDealingVO();
        String corpid = smsDealingDTO.getCorpid();
        Integer dataId = smsDealingDTO.getDataId();
        String mobile = smsDealingDTO.getMobile();
        if(StringUtil.isEmpty(mobile)){
            // 前端处理，空号码返回空值
            PageHelper pageHelper = new PageHelper(smsDealingDTO.getPage(), smsDealingDTO.getPageSize());
            pageHelper.setRowsCount(0);
            SmsReplyVO smsReplyVO = new SmsReplyVO();
            smsReplyVO.setReplySmsList(new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            smsReplyVO.setPageHelper(pageHelper);
            smsDealingVO.setReplySmsList(smsReplyVO);
            SmsSendVO smsSendVO = new SmsSendVO();
            smsSendVO.setSendSmsList(new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY));
            smsSendVO.setPageHelper(pageHelper);
            smsDealingVO.setSendSmsList(smsSendVO);
            return smsDealingVO;
        }
        Integer page = smsDealingDTO.getPage();
        Integer pageSize = smsDealingDTO.getPageSize();

        SmsSendVO sendSmsVO = new SmsSendVO();
        SmsReplyVO smsReplyVO = new SmsReplyVO();

        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("del", DelEnum.NORMAL.getDel());
        param.put("corpid", corpid);
        param.put("mobile", mobile);
        param.put("refId", dataId);
        param.put("page", page);
        param.put("orderByStr", "id desc");

        // 发送短信
        try {
            PageHelper pageHelper = PageHelperUtil.getPageHelper(param, smsStatusModel, pageSize);
            List<SmsStatusEntity> list = (List<SmsStatusEntity>) PageHelperUtil.getEntityList(param, pageHelper, smsStatusModel);
            List<SmsSendPojo> sendSmsList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(SmsStatusEntity entity : list){
                SmsSendPojo smsSendPojo = new SmsSendPojo();
                smsSendPojo.setContent(entity.getContent());
                smsSendPojo.setSmsStatus(entity.getStatus());
                String sendTime = null;
                if (entity.getSendTime() != null) {
                    sendTime = DateUtil.getString(entity.getSendTime() * 1000, SDFYMDHM);
                }
                smsSendPojo.setSmsTime(sendTime);
                sendSmsList.add(smsSendPojo);
            }
            sendSmsVO.setPageHelper(pageHelper);
            sendSmsVO.setSendSmsList(sendSmsList);
        } catch (Exception e) {
            LOG.error("发送短信记录列表查询失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        // 回复短信
        try {
            PageHelper pageHelper = PageHelperUtil.getPageHelper(param, smsReplyModel, pageSize);
            List<SmsReplyEntity> list = (List<SmsReplyEntity>) PageHelperUtil.getEntityList(param, pageHelper, smsReplyModel);
            List<SmsReplyPojo> replySmsList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for(SmsReplyEntity entity : list){
                SmsReplyPojo smsReplyPojo = new SmsReplyPojo();
                smsReplyPojo.setContent(entity.getContent());
                String replyTime = null;
                if (entity.getReplyTime() != null) {
                    replyTime = DateUtil.getString(entity.getReplyTime() * 1000, SDFYMDHM);
                }
                smsReplyPojo.setSmsTime(replyTime);
                replySmsList.add(smsReplyPojo);
            }
            smsReplyVO.setPageHelper(pageHelper);
            smsReplyVO.setReplySmsList(replySmsList);
        } catch (Exception e) {
            LOG.error("回复短信记录列表查询失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

        smsDealingVO.setSendSmsList(sendSmsVO);
        smsDealingVO.setReplySmsList(smsReplyVO);
        return smsDealingVO;
    }

    /**
     * 获取回复短信日志列表
     *
     * @param smsReplyLogListDTO 入参
     * @return
     * @author youli.chen
     * @date: 2019-11-25 19:59
     * @version v1.0
     * @since v1.0
     */
    @Override
    public SmsReplyLogListVO logList(SmsReplyLogListDTO smsReplyLogListDTO) throws XbbException {
        SmsReplyLogListVO smsReplyLogListVO = new SmsReplyLogListVO();

        String corpid = smsReplyLogListDTO.getCorpid();
        String userId = smsReplyLogListDTO.getUserId();

        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (userEntity == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
        }

        // 查询条件
        Integer refType = smsReplyLogListDTO.getRefType();
        String mobileLike = smsReplyLogListDTO.getMobileLike();
        String replyNameLike = smsReplyLogListDTO.getReplyNameLike();
        String contentLike = smsReplyLogListDTO.getContentLike();
        List<String> timeSpan = smsReplyLogListDTO.getTimeSpan();
        Integer page = smsReplyLogListDTO.getPage();
        Integer pageSize = smsReplyLogListDTO.getPageSize();

        mobileLike = mobileLike != null ? mobileLike.trim() : null;
        replyNameLike = replyNameLike != null ? replyNameLike.trim() : null;
        contentLike = contentLike != null ? contentLike.trim() : null;
        Integer startTimeF = null;
        Integer endTimeF = null;
        if (timeSpan != null && timeSpan.size() != 0) {
            startTimeF = DateUtil.getInt(timeSpan.get(0), DateUtil.SDFDate);
            endTimeF = DateUtil.getInt(timeSpan.get(1), DateUtil.SDFDate) + RedisConstant.LONG_DURATION;
        }

        // 获取某个员工的下属员工列表,管理员可以查看公司所有下属,包含离职员工，不排除自己
        Integer dataPermission = userModel.getDataPermission(userEntity, true);
        List<String> subUserIdIn = userModel.getSubIdListByDataPermission(dataPermission, userEntity.getUserId(), userEntity.getCorpid(),BasicConstant.ONE,false);
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("corpid", corpid);
            param.put("refType", refType);
            param.put("mobileLike", mobileLike);
            param.put("replyNameLike", replyNameLike);
            param.put("contentLike", contentLike);
            param.put("startTime", startTimeF);
            param.put("endTime", endTimeF);
            param.put("senderIdIn", subUserIdIn);
            param.put("orderByStr", "id desc");
            param.put("page", page);

            PageHelper pageHelper = PageHelperUtil.getPageHelper(param, smsReplyModel, pageSize);
            List<SmsReplyEntity> list = (List<SmsReplyEntity>) PageHelperUtil.getEntityList(param, pageHelper, smsReplyModel);
            List<SmsReplyLogPojo> resultList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (SmsReplyEntity entity : list) {
                String replyTime = null;
                if (entity.getReplyTime() != null) {
                    replyTime = DateUtil.getString(entity.getReplyTime() * 1000, SDFYMDHM);
                }
                String refName = "";
                if(entity.getRefType() != null){
                    SmsModuleTypeEnum smsModuleTypeEnum = SmsModuleTypeEnum.getByCode(entity.getRefType());
                    refName = smsModuleTypeEnum == null ? "" : smsModuleTypeEnum.getName();
                }

                SmsReplyLogPojo pojo = new SmsReplyLogPojo();
                BeanUtil.copyProperties(entity, pojo);
                pojo.setRefTypeName(refName);
                SmsExplainPojo smsExplainPojo = new SmsExplainPojo();
                smsExplainPojo.setDataId(entity.getRefId());
                smsExplainPojo.setAppId(entity.getAppId());
                smsExplainPojo.setMenuId(entity.getMenuId());
                smsExplainPojo.setFormId(entity.getFormId());
                smsExplainPojo.setBusinessType(entity.getRefType());
                smsExplainPojo.setSubBusinessType(entity.getRefType());
                smsExplainPojo.setSaasMark(entity.getSaasMark());
                pojo.setReplyTime(replyTime);
                pojo.setEntity(smsExplainPojo);
                pojo.setJump(entity.getRefId() == null ? false : true);
                resultList.add(pojo);
            }

            smsReplyLogListVO.setPageHelper(pageHelper);
            smsReplyLogListVO.setList(resultList);
        } catch (Exception e) {
            LOG.error("查询回复短信记录列表失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return smsReplyLogListVO;
    }
}
